package com.scalar.chiptrack.operations.process;

import java.awt.Rectangle;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Iterator;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.scalar.ScalarException;
import com.scalar.chiptrack.commons.Constants;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.db.DBXException;
import com.scalar.chiptrack.operations.process.dao.WorkflowDBManager;
import com.scalar.chiptrack.operations.process.dao.gp.GPWorkFlowDAO;
import com.scalar.chiptrack.utils.ConfigManager;

public class WorkflowProcess
{
	private final static String XMLNS = "http://www.wfmc.org/2002/XPDL1.0";
	private final static String XMLNS_XPDL = "http://www.wfmc.org/2002/XPDL1.0";
	private final static String XMLNS_XSI = "http://www.w3.org/2001/XMLSchema-instance";
	private final static String XSI_SCHEMA_LOCATION = "http://www.wfmc.org/2002/XPDL1.0 http://wfmc.org/standards/docs/TC-1025_schema_10_xpdl.xsd";

	public static String saveProcessToDB( ByteArrayInputStream bais , String productName ,String filePath ,String location)
	{
		ArrayList activityCollection 	= new ArrayList();
		ArrayList transitionCollection 	= new ArrayList();
		DBTransaction dbTransaction 	= null;
		String flag 					= "failure" ;
        WorkflowDBManager workFlowdb 	= new WorkflowDBManager();
		try
		{
			Document document 				= null;
			DocumentBuilderFactory dbf 		= DocumentBuilderFactory.newInstance();
			DocumentBuilder builder 		= dbf.newDocumentBuilder();
			document 						= builder.parse( bais );

			buildActivitiesAndTransitionCollection( document, activityCollection, transitionCollection );

			if( location.equals("Database") )
			{
                String baseProductId = null;
				dbTransaction = DBTransaction.getInstance();
				dbTransaction.begin();		
				workFlowdb.errors = "";
				workFlowdb.saveActivityCollection( dbTransaction, activityCollection, productName );
				HashMap activityIdProcessstepIDMap = createMap( activityCollection );
				workFlowdb.saveTransitionCollection( dbTransaction, transitionCollection ,activityIdProcessstepIDMap ,productName );
                baseProductId = WorkflowDBManager.getProductId(dbTransaction, productName);
                workFlowdb.updatePartNumberComments(dbTransaction, baseProductId );
			}
			writeFile( productName, activityCollection, transitionCollection, filePath);
            flag = "success";
        }
		catch(Exception e)
		{
            if ( workFlowdb.errors != null && workFlowdb.errors.length() > 0 )
            {
              flag = workFlowdb.errors;
            }
            workFlowdb.errors = "";
			e.printStackTrace();
		}
		finally 
		{
			if (flag.equals("success")) 
			{
				try{
					if( dbTransaction != null )
						dbTransaction.commit();
				}
				catch (DBXException e1){
					e1.printStackTrace();
				}                                                           
			}
			else 
			{
				try{
					if( dbTransaction != null )
						dbTransaction.rollback();
				}catch (DBXException e1){
				   e1.printStackTrace();
				}
			}
		}
		
		if( flag.equalsIgnoreCase( "success" ) )
		{
			if( Constants.SALES_INTEGRATION_TYPE_GREAT_PLAINS.equals( ConfigManager.getSalesIntegrationType() ) )
			{
				if( location.equals( "Database" ) )
				{
					try
	                {
						dbTransaction = null;
	                    dbTransaction = DBTransaction.getInstance();
	                    dbTransaction.begin();
						GPWorkFlowDAO.saveProducts( dbTransaction, activityCollection );
	                }
	                catch (Exception e)
	                {
	                    e.printStackTrace();
	                }
	                finally
	                {
						try{
							if( dbTransaction != null )
								dbTransaction.commit();
						}catch (DBXException e1){
						   e1.printStackTrace();
						}
	                }
				}			
			}
		}

		if( flag.equals("success") )
		try
		{
			Thread.sleep( 5000 );
		}
		catch(Exception e)
		{
			// ignore
		}

		return flag;
	}
	
	
	/**
     * @param productName
     * @param activityCollection
     * @param transitionCollection
     */
    public static void writeFile(String productName, ArrayList activityCollection, ArrayList transitionCollection, String filePath)
    {
		Document document = null;
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder;
        try
        {
            builder = dbf.newDocumentBuilder();
			document = builder.newDocument();
			Node node = document.createElement("Package");
			((Element)node).setAttribute("Id", productName);
			((Element)node).setAttribute("xmlns", XMLNS);
			((Element)node).setAttribute("xmlns:xpdl", XMLNS_XPDL);
			((Element)node).setAttribute("xmlns:xsi", XMLNS_XSI);
			((Element)node).setAttribute("xsi:schemaLocation", XSI_SCHEMA_LOCATION);
			Node workflowProcesses = (node.getOwnerDocument()).createElement("Workflowprocesses");

			Node workflowProcess = (workflowProcesses.getOwnerDocument()).createElement("workflowprocess");
			((Element)workflowProcess).setAttribute("Id", productName+"_Work");
			cellmapToXML(workflowProcess, productName, activityCollection );
			edgemapToXML(workflowProcess, productName, transitionCollection );
			workflowProcesses.appendChild(workflowProcess);
			node.appendChild(workflowProcesses);
			document.appendChild(node);
        }
        catch (ParserConfigurationException e)
        {
            e.printStackTrace();
        }
		File f = null;
		try
		{
			f = new File( filePath );

			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			RandomAccessFile raf = new RandomAccessFile(f, "rw");
            TransformerFactory tFactory = TransformerFactory.newInstance();
            Transformer transformer = tFactory.newTransformer();
            transformer.setOutputProperty("indent","yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount","4");
            transformer.setOutputProperty("encoding","UTF-8");

            DOMSource source = new DOMSource( document );
            StreamResult result = new StreamResult( baos );
            transformer.transform( source , result );
            raf.setLength( baos.size() );
            raf.write( baos.toByteArray() );
			baos.flush();
			baos.close();
			raf.close();
        }
		catch(Exception e)
		{
			e.printStackTrace();
		}
    }
    
	public static void cellmapToXML(Node parent, String name, ArrayList activityCollection )
	{
		Node activities = (parent.getOwnerDocument()).createElement("Activities");
	
		for(int i=0; i < activityCollection.size(); i++)
		{
			Map map = (Map)activityCollection.get(i);
			Node activity = (activities.getOwnerDocument()).createElement("Activity");
			
			String attrId =  name+"_Act_"+(i+1);
			String processStepId = null;
			String tempId = null;
			String type = "";
			
			if( map.containsKey("processStepId") )
				processStepId = (String)map.get("processStepId");
			
			if( processStepId == null)
			{
				map.put("processStepId", "");
			}
			
			if( map.containsKey("attrId") ) 
				tempId = (String)map.get("attrId");
			
			if( tempId == null)
			{
				map.put("attrId", attrId);
			}
			else
			{
				attrId = tempId;
			}
			
			((Element)activity).setAttribute("Id", attrId);
			
			Object tempValue = "";
			if( map.containsKey( "value" ) )
				tempValue = map.get("value");
			
			if(tempValue instanceof String)
			{
				((Element)activity).setAttribute("name", (String)tempValue);
			}
			
			if( map.containsKey("Type") )
				type = (String)map.get("Type");
				
			((Element)activity).setAttribute("Type", type);
			
			Node extendedAttributes = (activity.getOwnerDocument()).createElement("ExtendedAttributes");
			Node extendedAttribute =(extendedAttributes.getOwnerDocument()).createElement("ExtendedAttribute"); 
			
			if( map.containsKey("bounds") )
			{
				Rectangle r = (Rectangle)map.get("bounds");
				((Element)extendedAttribute).setAttribute("Name", "bounds");
				((Element)extendedAttribute).setAttribute("Value", ("X:"+r.x+";"+"Y:"+r.y+";"+"W:"+r.width+";"+"H:"+r.height));
			}
			else
			{
				((Element)extendedAttribute).setAttribute("Name", "bounds");
				((Element)extendedAttribute).setAttribute("Value", ("X:"+10+";"+"Y:"+10+";"+"W:"+70+";"+"H:"+30));
			}
			
			extendedAttributes.appendChild(extendedAttribute);
			
			extendedAttribute = (extendedAttributes.getOwnerDocument()).createElement("ExtendedAttribute"); 
			
			((Element)extendedAttribute).setAttribute("Name", "processStepId");
			((Element)extendedAttribute).setAttribute("Value", processStepId);
			
			extendedAttributes.appendChild(extendedAttribute);
			
			extendedAttribute =(extendedAttributes.getOwnerDocument()).createElement("ExtendedAttribute"); 
			
			((Element)extendedAttribute).setAttribute("Name", "partnumber");
			
			if( map.containsKey( "partnumber") )
				((Element)extendedAttribute).setAttribute("Value", (String)map.get("partnumber"));
			else	
				((Element)extendedAttribute).setAttribute("Value", "");
			
			extendedAttributes.appendChild(extendedAttribute);

            extendedAttribute =(extendedAttributes.getOwnerDocument()).createElement("ExtendedAttribute");
                ((Element)extendedAttribute).setAttribute("Name", "partStatus");
                ((Element)extendedAttribute).setAttribute("Value", map.get("partStatus") != null ? (String)map.get("partStatus") : "Prod" );
            extendedAttributes.appendChild(extendedAttribute);

            if ( processStepId == null || processStepId.trim().length() == 0 ) //only unsaved product details are saving to file
            {
                extendedAttribute =(extendedAttributes.getOwnerDocument()).createElement("ExtendedAttribute");
                ((Element)extendedAttribute).setAttribute("Name", "parameters");
                if( map.containsKey( "parameters") )
                    ((Element)extendedAttribute).setAttribute("Value", (String)map.get("parameters"));
                else
                    ((Element)extendedAttribute).setAttribute("Value", "");
                extendedAttributes.appendChild(extendedAttribute);

                extendedAttribute =(extendedAttributes.getOwnerDocument()).createElement("ExtendedAttribute");
                ((Element)extendedAttribute).setAttribute("Name", "dupPartNumbers");
                if( map.containsKey("dupPartNumbers") )
                    ((Element)extendedAttribute).setAttribute("Value", (String)map.get("dupPartNumbers"));
                else
                    ((Element)extendedAttribute).setAttribute("Value", "");
                extendedAttributes.appendChild(extendedAttribute);
			
			    extendedAttribute =(extendedAttributes.getOwnerDocument()).createElement("ExtendedAttribute");
                ((Element)extendedAttribute).setAttribute("Name", "comments");
                if( map.containsKey("comments") )
                    ((Element)extendedAttribute).setAttribute("Value", (String)map.get("comments"));
                else
                    ((Element)extendedAttribute).setAttribute("Value", "");
                extendedAttributes.appendChild(extendedAttribute);
			
			    extendedAttribute =(extendedAttributes.getOwnerDocument()).createElement("ExtendedAttribute");
			    ((Element)extendedAttribute).setAttribute("Name", "vendors");/*
                if( map.containsKey("vendors") )
                    ((Element)extendedAttribute).setAttribute("Value", (String)map.get("vendors"));
                else
                    ((Element)extendedAttribute).setAttribute("Value", "");
                extendedAttributes.appendChild(extendedAttribute);*/
                if( map.containsKey("vendors") )
                {
                    String vendorsString = (String)map.get("vendors");
                    ArrayList vendors = WorkflowDBManager.parseString(vendorsString, '#');
                    String vendorDetails;
                    for (int vendorCounter = 0; vendorCounter < vendors.size() ; vendorCounter++ )
                    {
                        Node vendor =(extendedAttributes.getOwnerDocument()).createElement("Vendor");
                        vendorDetails = (String)vendors.get(vendorCounter);
                        if ( vendorDetails != null && vendorDetails.trim().length() > 0 )
                        {
                            ArrayList vendorAttributes = WorkflowDBManager.parseString( vendorDetails, ';' );

                            for ( int vendAttr = 0; vendAttr < vendorAttributes.size() && vendorAttributes.size() != 0 ; vendAttr++ )
                            {

                                Node vendorAttribute =(extendedAttribute.getOwnerDocument()).createElement("VendorAttribute");
                                switch ( vendAttr )
                                {
                                    case 0:
                                        ((Element)vendorAttribute).setAttribute("Name", "select");
                                        ((Element)vendorAttribute).setAttribute("Value", (String)vendorAttributes.get(vendAttr));
                                        break;
                                    case 1:
                                        ((Element)vendorAttribute).setAttribute("Name", "priority");
                                        ((Element)vendorAttribute).setAttribute("Value", (String)vendorAttributes.get(vendAttr));
                                        break;
                                    case 2:
                                        ((Element)vendorAttribute).setAttribute("Name", "locationName");
                                        ((Element)vendorAttribute).setAttribute("Value", (String)vendorAttributes.get(vendAttr));
                                        break;
                                    case 3:
                                        ((Element)vendorAttribute).setAttribute("Name", "split");
                                        ((Element)vendorAttribute).setAttribute("Value", (String)vendorAttributes.get(vendAttr));
                                        break;
                                    case 4:
                                        ((Element)vendorAttribute).setAttribute("Name", "capacity/weeek");
                                        ((Element)vendorAttribute).setAttribute("Value", (String)vendorAttributes.get(vendAttr));
                                        break;
                                    case 5:
                                        ((Element)vendorAttribute).setAttribute("Name", "cycleTimeNormal");
                                        ((Element)vendorAttribute).setAttribute("Value", (String)vendorAttributes.get(vendAttr));
                                        break;
                                    case 6:
                                        ((Element)vendorAttribute).setAttribute("Name", "cycleTimeExpress");
                                        ((Element)vendorAttribute).setAttribute("Value", (String)vendorAttributes.get(vendAttr));
                                        break;
                                }
                                vendor.appendChild(vendorAttribute);
                            }
                            extendedAttribute.appendChild(vendor);
                        }
                    }
                    extendedAttributes.appendChild(extendedAttribute);
                }

                if( map.containsKey("mktPartNumber") )
                {
                    extendedAttribute =(extendedAttributes.getOwnerDocument()).createElement("ExtendedAttribute");
                    ((Element)extendedAttribute).setAttribute("Name", "mktPartNumber");
                    ((Element)extendedAttribute).setAttribute("Value", (String)map.get("mktPartNumber"));
                    extendedAttributes.appendChild(extendedAttribute);
                }
                if( map.containsKey("isApprovedProduct") )
                {
                    extendedAttribute =(extendedAttributes.getOwnerDocument()).createElement("ExtendedAttribute");
                    ((Element)extendedAttribute).setAttribute("Name", "isApprovedProduct");
                    ((Element)extendedAttribute).setAttribute("Value", (String)map.get("isApprovedProduct"));
                    //System.out.println("IS APPROVED PRODUCT "+ (String)map.get("isApprovedProduct") );
                    extendedAttributes.appendChild(extendedAttribute);
                }
                if( map.containsKey("isPrimaryFGProduct") )
                {
                    extendedAttribute =(extendedAttributes.getOwnerDocument()).createElement("ExtendedAttribute");
                    ((Element)extendedAttribute).setAttribute("Name", "isPrimaryFGProduct");
                    ((Element)extendedAttribute).setAttribute("Value", (String)map.get("isPrimaryFGProduct"));
                    extendedAttributes.appendChild(extendedAttribute);
                }
                if( map.containsKey("binsRequired") )
                {
                    extendedAttribute =(extendedAttributes.getOwnerDocument()).createElement("ExtendedAttribute");
                    ((Element)extendedAttribute).setAttribute("Name", "binsRequired");
                    ((Element)extendedAttribute).setAttribute("Value", (String)map.get("binsRequired"));
                    extendedAttributes.appendChild(extendedAttribute);
                }
                if( map.containsKey("goodBinNumber") )
                {
                    extendedAttribute =(extendedAttributes.getOwnerDocument()).createElement("ExtendedAttribute");
                    ((Element)extendedAttribute).setAttribute("Name", "goodBinNumber");
                    ((Element)extendedAttribute).setAttribute("Value", (String)map.get("goodBinNumber"));
                    extendedAttributes.appendChild(extendedAttribute);
                }
                if( map.containsKey("rejectedBinNumber") )
                {
                    extendedAttribute =(extendedAttributes.getOwnerDocument()).createElement("ExtendedAttribute");
                    ((Element)extendedAttribute).setAttribute("Name", "rejectedBinNumber");
                    ((Element)extendedAttribute).setAttribute("Value", (String)map.get("rejectedBinNumber"));
                    extendedAttributes.appendChild(extendedAttribute);
                }

                extendedAttribute =(extendedAttributes.getOwnerDocument()).createElement("ExtendedAttribute");
                ((Element)extendedAttribute).setAttribute("Name", "partStatus");
                ((Element)extendedAttribute).setAttribute("Value", map.get("partStatus") != null ? (String)map.get("partStatus") : "Prod" );
                extendedAttributes.appendChild(extendedAttribute);

                extendedAttribute =(extendedAttributes.getOwnerDocument()).createElement("ExtendedAttribute");
                ((Element)extendedAttribute).setAttribute("Name", "productGroup");
                ((Element)extendedAttribute).setAttribute("Value", map.get("productGroup") != null ? (String)map.get("productGroup") : "Prod" );
                extendedAttributes.appendChild(extendedAttribute);
            }
            activity.appendChild(extendedAttributes);
			activities.appendChild(activity);
		}
		
		parent.appendChild(activities);
	}
	
	public static void edgemapToXML(Node parent, String name, ArrayList transitionCollection)
	{
		Node transitions = (parent.getOwnerDocument()).createElement("Transitions");
		
		for(int i=0; i < transitionCollection.size(); i++)
		{
			Map map = (HashMap)transitionCollection.get(i);
			String from = (String)map.get("From");
			String to = (String)map.get("To");
			String edgeId = name+"_Tran_"+(i+1);
			
			if(map.get("edgeId") == null)
			{
				map.put("edgeId", edgeId);
			}
			
			String transitionStepId = (String)map.get("transitionStepId");
			
			if(transitionStepId == null){
				map.put("transitionStepId", "");
			}
			
			String value = (String)map.get("value");
			if(value == null){
				value = "Transition";
			}
			
			Node transition = (transitions.getOwnerDocument()).createElement("Transition");
			((Element)transition).setAttribute("Id", edgeId);
			((Element)transition).setAttribute("From", from);
			((Element)transition).setAttribute("To", to);
			((Element)transition).setAttribute("Name", value);
			
			Node extendedAttributes = (transition.getOwnerDocument()).createElement("ExtendedAttributes");
			Node extendedAttribute =(extendedAttributes.getOwnerDocument()).createElement("ExtendedAttribute"); 
			
			Rectangle r = (Rectangle)map.get("bounds");
			((Element)extendedAttribute).setAttribute("Name", "bounds");
			((Element)extendedAttribute).setAttribute("Value", ("X:"+r.x+";"+"Y:"+r.y+";"+"W:"+r.width+";"+"H:"+r.height));
			
			extendedAttributes.appendChild(extendedAttribute);
			
			extendedAttribute =(extendedAttributes.getOwnerDocument()).createElement("ExtendedAttribute"); 
			((Element)extendedAttribute).setAttribute("Name", "transitionStepId");
			((Element)extendedAttribute).setAttribute("Value", transitionStepId);
			
			extendedAttributes.appendChild(extendedAttribute);
			
			extendedAttribute = ( extendedAttributes.getOwnerDocument() ).createElement( "ExtendedAttribute" ); 
			( (Element)extendedAttribute ).setAttribute( "Name", "transportLocations" );
			if( map.containsKey( "transportLocations" ) )
			{
				( (Element)extendedAttribute ).setAttribute( "Value", (String)map.get("transportLocations") );
			}
			else
				( (Element)extendedAttribute ).setAttribute( "Value", "" );
			
			extendedAttributes.appendChild( extendedAttribute );

			transition.appendChild(extendedAttributes);
			transitions.appendChild(transition);
		}
		
		parent.appendChild(transitions);
	}


    public static void buildActivitiesAndTransitionCollection(Document parent, ArrayList activities, ArrayList transitionList){
		
	   NodeList nodeList = parent.getElementsByTagName("Activities");
			
	   for( int i = 0; i < nodeList.getLength(); i++ )
	   {
		   Element element 		= (Element)nodeList.item( i );
		   NodeList activity 	= element.getElementsByTagName( "Activity" );
		   createActivityMaps( activity, activities );
	   }
	   nodeList 		= parent.getElementsByTagName("Transitions");
	   
	   for( int i = 0; i < nodeList.getLength(); i++ )
	   {
		   Element element 		= (Element)nodeList.item(i);
		   NodeList transition 	= element.getElementsByTagName( "Transition" );
		   createTransitionMaps( transition, transitionList );
	   }
   }
   
   public  static void createActivityMaps(NodeList activity, ArrayList list)
   {
	   Map map = null;
       
	   for(int i=0; i<activity.getLength(); i++)
	   {
		   Element element = (Element)activity.item(i);
		   map = new HashMap();
		   //map.put( "value", element.getAttribute( "value" ) );
		   map.put( "value", element.getAttribute( "name" ) );
		   //map.put( "name", element.getAttribute( "name" ) );
		   map.put( "attrId", element.getAttribute( "Id" ) );
		   map.put( "Type", element.getAttribute( "Type" ));

		   NodeList extendedAttribute = element.getElementsByTagName( "ExtendedAttribute" );
			
		   for(int extAttr =0; extAttr<extendedAttribute.getLength(); extAttr++)
		   {
			   element = (Element)extendedAttribute.item(extAttr);
				
			   if(element.getAttribute("Name").equalsIgnoreCase("bounds")){
				   String value = element.getAttribute("Value");
				   map.put("bounds", getRectangle(value));
			   }
				
			   if(element.getAttribute("Name").equalsIgnoreCase("processStepId")){
				   map.put("processStepId", element.getAttribute("Value"));
			   }
				
			   if(element.getAttribute("Name").equalsIgnoreCase("partnumber")){
				   map.put("partnumber", element.getAttribute("Value"));
			   }
			   if(element.getAttribute("Name").equalsIgnoreCase("parameters")){
				   map.put("parameters", element.getAttribute("Value"));
			   }
			   if(element.getAttribute("Name").equalsIgnoreCase("dupPartNumbers"))
			   {
				   map.put("dupPartNumbers", element.getAttribute("Value"));
			   }
			   if(element.getAttribute("Name").equalsIgnoreCase("mktPartNumber"))
			   {
				   map.put("mktPartNumber", element.getAttribute("Value"));
			   }
			   if(element.getAttribute("Name").equalsIgnoreCase("comments"))
			   {
				   map.put("comments", element.getAttribute("Value"));
			   }
			   if(element.getAttribute("Name").equalsIgnoreCase("vendors"))
			   {
				   //map.put("vendors", element.getAttribute("Value"));
                   StringBuffer vendorString = new StringBuffer(300);
                   NodeList vendorNodeList = element.getElementsByTagName("Vendor");
                   Element vendorElement;
                   for(int vendorNodes =0; vendorNodes < vendorNodeList.getLength(); vendorNodes++)
                   {
                       vendorElement = (Element)vendorNodeList.item(vendorNodes);
                       NodeList vendorAttributes = vendorElement.getElementsByTagName("VendorAttribute");
                       Element vendorAttributeElement;
                       for(int vendorAttr =0; vendorAttr < vendorAttributes.getLength(); vendorAttr++)
                       {
                            vendorElement = (Element)vendorAttributes.item(vendorAttr);
                            vendorString.append(vendorElement.getAttribute("Value"));
                            vendorString.append(";");
                       }
                       vendorString.deleteCharAt( vendorString.length() - 1 );
                       vendorString.append("#");
                   }
                   map.put("vendors", vendorString.toString());
			   }
			   if(element.getAttribute("Name").equalsIgnoreCase("isApprovedProduct"))
			   {
			   		map.put("isApprovedProduct", element.getAttribute("Value"));
			   }
               if(element.getAttribute("Name").equalsIgnoreCase("isPrimaryFGProduct"))
			   {
			   		map.put("isPrimaryFGProduct", element.getAttribute("Value"));
			   }
               if(element.getAttribute("Name").equalsIgnoreCase("goodBinNumber"))
			   {
			   		map.put("goodBinNumber", element.getAttribute("Value"));
			   }
			   if(element.getAttribute("Name").equalsIgnoreCase("rejectedBinNumber"))
			   {
			   		map.put("rejectedBinNumber", element.getAttribute("Value"));
			   }
			   if(element.getAttribute("Name").equalsIgnoreCase("binsRequired"))
			   {
					map.put("binsRequired", element.getAttribute("Value"));
			   }
               if(element.getAttribute("Name").equalsIgnoreCase("partStatus"))
			   {                      
					map.put("partStatus", element.getAttribute("Value"));
			   }
               if(element.getAttribute("Name").equalsIgnoreCase("productGroup"))
			   {
					map.put("productGroup", element.getAttribute("Value"));
			   }
           }
		   list.add(map);
	   }
   }
	
	public static void createTransitionMaps( NodeList transition, ArrayList list )
   	{
		Map map = null;
	
	   	for( int i = 0; i < transition.getLength(); i++ )
	   	{
			Element element 	= (Element)transition.item( i );
		   	map 				= new HashMap();
		   	map.put( "value", element.getAttribute( "name" ) );
		   	map.put( "From", element.getAttribute( "From" ) );
		   	map.put( "To", element.getAttribute( "To" ) );
			
		   	NodeList extendedAttribute = element.getElementsByTagName( "ExtendedAttribute" );
		
		   	for( int extAttr = 0; extAttr < extendedAttribute.getLength(); extAttr++ )
		   	{
				element = (Element)extendedAttribute.item( extAttr );
			
			   	if( element.getAttribute( "Name" ).equalsIgnoreCase( "bounds" ) )
			   	{
					String value = element.getAttribute( "Value" );
				   	map.put( "bounds", getRectangle( value ) );
			   	}
			
			   	if( element.getAttribute( "Name" ).equalsIgnoreCase( "transitionStepId" ) )
			   	{
					map.put( "transitionStepId", element.getAttribute( "Value" ) );
			   	}

				if( element.getAttribute( "Name" ).equalsIgnoreCase( "transportLocations" ) )
				{
					map.put( "transportLocations", element.getAttribute( "Value" ) );
				}
		   }
		   list.add( map );
	   }
   }
   
   
   public static Rectangle getRectangle(String bounds){
		
	   int length = bounds.length();
	   int index = bounds.indexOf(":");
	   bounds = bounds.substring(index, length);
	   int semiIndex = bounds.indexOf(";");
	   int X = Integer.parseInt(bounds.substring(index, semiIndex));
	   bounds = bounds.substring(semiIndex+1, bounds.length());
	   length = bounds.length();
	   index = bounds.indexOf(":");
	   bounds = bounds.substring(index, length);
	   semiIndex = bounds.indexOf(";");
	   int Y = Integer.parseInt(bounds.substring(index, semiIndex));
	   bounds = bounds.substring(semiIndex+1, bounds.length());
	   length = bounds.length();
	   index = bounds.indexOf(":");
	   bounds = bounds.substring(index, length);
	   semiIndex = bounds.indexOf(";");
	   int W = Integer.parseInt(bounds.substring(index, semiIndex));
	   bounds = bounds.substring(semiIndex+1, bounds.length());
	   length = bounds.length();
	   index = bounds.indexOf(":");
	   bounds = bounds.substring(index+1, length);
	   int H = Integer.parseInt(bounds);
	   return new Rectangle(X, Y, W, H);
   }
  
  	private static HashMap createMap(ArrayList activityCollection)
	{
		HashMap idProcessStepmap = new HashMap();
		for( int i=0 ; i < activityCollection.size() ; i++  )
		{
			HashMap map = (HashMap)activityCollection.get(i);
			if( map.containsKey("processStepId") && map.get("processStepId")!= null )
			{
				if( map.containsKey("attrId") )
					idProcessStepmap.put( map.get("attrId"),map.get("processStepId") );
			}
		}
		return idProcessStepmap;
	}

    public static String getDupPartNumbers( String productNameParameter ) throws NumberFormatException, ScalarException
    {
    	String duplicateNames 	= "";
		duplicateNames 			= WorkflowDBManager.getDuplicatePartNumbers( productNameParameter );
        return duplicateNames;
    }


    public static String saveProcessToFile(ByteArrayInputStream bais, String string)
    {
    	String flag = "failure";
        return null;
    }


    /**
     * @param productNameParameter
     * @return Duplicate M
     */
    public static String getDupMktPartNumbers( String productNameParameter ) throws ScalarException
    {
		String duplicateNames 	= "";
		duplicateNames 			= WorkflowDBManager.getDuplicateMktPartNumbers( productNameParameter );
		return duplicateNames;
    }

    public static void buildFileFromDB( String productName, String filePath ) throws ScalarException
    {
    	HashMap activityCollectionMap = WorkflowDBManager.getActivityMap( productName );
    	ArrayList activityCollectionList 	= new ArrayList();
    	Iterator activityCollectionMapIterator = activityCollectionMap.keySet().iterator();
    	int i = 1;

    	while( activityCollectionMapIterator.hasNext() )
    	{
    		Map map = (Map)activityCollectionMap.get( activityCollectionMapIterator.next() );
    		String attrId =  productName + "_Act_" + (i++);
    		map.put( "attrId", attrId );
    		activityCollectionList.add( map );
    	}

    	ArrayList transitionCollectionList 	= WorkflowDBManager.getTransitionMap( productName, activityCollectionMap );

    	writeFile( productName, activityCollectionList, transitionCollectionList, filePath );
    }
}